<?php


namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\GameData;
use app\admin\model\GameRecord;
use app\admin\model\User;
use think\Db;

class Game extends Api
{
    protected $noNeedLogin = ['gamelist', 'gamerecord'];
    protected $noNeedRight = ['*'];
    /**
     * 保存游戏参数
     *
     * @param int $token  用户id
     * @param int $game_id 游戏id
     * @param string $data 游戏参数
     */
    public function gamedata()
    {
        $where['user_id'] = $this->auth->id;
        $this->checkParam(['game_id']);
        $where['game_id'] = $this->request->param('game_id');
        $data = $this->request->param('data');
        //dump($data);die;
        $game_data = GameData::where($where)->find();

        $game = Db::name('game')->where('id',$where['game_id'])->where('status', 1)->find();
        if (!$game) {
            $this->error(__('Please check the game parameters'));
        }

        if (!empty($data)){
            $data = json_decode(htmlspecialchars_decode($data),'true');
            $data = json_encode($data);
            if ($game_data) {
                GameData::where($where)->update(['data' => $data]);
                $msg = 'Modified successfully';
            } else {
                GameData::insert([
                    'user_id' => $where['user_id'],
                    'game_id' => $where['game_id'],
                    'data' => $data,
                    'addtime' => date('Y-m-d H:i:s',time())
                ]);
                $msg = 'Saved successfully';
            }
        } else {
            $msg = 'Request successful';
        }
        $res = GameData::where($where)->find();

        $res['data'] = empty($res['data']) ? $res['data'] : json_decode($res['data']);
        $this->success($msg, $res);
    }

    /**
     * 获取游戏列表参数
     */

    public function gamelist()
    {
        $this->success('successful', Db::name('game')->where('status', 1)->select());
    }

    /**
     * 保存游戏记录
     *
     * @param int $token  用户id
     * @param int $game_id 游戏id
     */
    public function gamerecord()
    {
        $uid = $this->auth->id;
        $this->checkParam(['game_id']);
        $game_id = $this->request->param('game_id');

        $game = Db::name('game')->where('id', $game_id)->where('status', 1)->find();
        if (!$game) {
            $this->error(__('Please check the game parameters'));
        }

        $user = User::where('id', $uid)->find();
        $data = [
            'user_id' => $uid,
            'app_id' => $user['app_id'],
            'game_id' => $game_id,
            'addtime' => date('Y-m-d H:i:s',time()),
        ];
        GameRecord::insert($data);
        $this->success('Saved successfully');
    }

}

